package org.baiyun.kaka.front.action;


import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;
import org.baiyun.kaka.entity.User;
import org.baiyun.kaka.form.UserForm;
import org.baiyun.kaka.service.IUserService;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

public class RegAction extends ActionSupport implements ModelDriven<UserForm>{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6396115952280604150L;

	private IUserService userService;
	
	private UserForm userForm= new UserForm();
	
	private String m;
	
	public String getM() {
		return m;
	}

	public void setM(String m) {
		this.m = m;
	}

	public UserForm getUserForm() {
		return userForm;
	}

	public void setUserForm(UserForm userForm) {
		this.userForm = userForm;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	
	@InputConfig(resultName="error")
	public String register() {
		
		HttpServletRequest  request = (HttpServletRequest)ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);		
		//String m = request.getParameter("m"); 		
	    //if (m!=null && m!="" && m.equals("d")) {
		
		if ("get".equals(request.getMethod().toLowerCase())) {
	    	return Action.INPUT;
	    }else {
	    	User user = new User();
	    	user.setId(userForm.getId());
	    	user.setEmail(userForm.getEmail());
	    	user.setPassword(userForm.getPwd1());
	    	user.setName(userForm.getName());
	    	userService.save(user);
	    	return Action.SUCCESS;
	    }
	}

	
	public void validateRegister() {

		
//		HttpServletRequest  request = (HttpServletRequest)ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);	
//		 if (m!=null && m!="" && m.equals("d"))  {
//	    	return;
//	    }		
//		

		HttpServletRequest  request = (HttpServletRequest)ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);	
	    if ("get".equals(request.getMethod().toLowerCase())) {
	    	return;
	    }
	    
		List<User> userList = userService.findUserByName(userForm.getName());
		if (userList.size()>0) {
           addFieldError("user_name_wrong", "");        
		}
		
	}

	@Override
	public UserForm getModel() {
		return this.userForm;
	}


	
	

}
